<?php

namespace App\Http\Controllers\Api;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Auth;
use App\User;
use App\Http\Requests\Api\SendMessageRequest;
use App\Model\Message;
use App\Model\MessageText;
use DB;


class MessageController extends Controller
{
    /*
    *发送消息
    */
    public function sendMessage(SendMessageRequest $request) {
    	$data = $request->all();
    	$toId = trim($data['toId']);
    	$toIdArr = explode(',', $toId);
    	/*验证用户是否可以群发*/
    	$user = Auth::user()->toArray();
    	if(count($toIdArr)>0) {
    		if($user['type']!=1) {
    			return response()->json(['code'=>400,'message'=>'您没有权限给多人发送消息']);
    		}
    	}
    	

    	$message_text = array();
    	$message_text['title'] = $data['title'];
    	$message_text['content'] = $data['content'];
    	$message_text['attachment'] = isset($data['attachment'])?$data['attachment']:'';
        $message_text['file_name'] = $data['file_name'];
    	$message_text['add_time'] = time();
    	
    	DB::beginTransaction();
    	try{ 
    		$message_text_res = MessageText::create($message_text);
	    	if($message_text_res) {
	    		/*插入关联信息*/
	    		$message_arr = array();
		    	foreach($toIdArr as $k=>$v) {
		    		$insert_data = array();
		    		$insert_data['from_id'] = $user['id'];
		    		$insert_data['to_id'] = $v;
		    		$insert_data['message_id'] = $message_text_res->id;
		    		$message_arr[] = $insert_data;
		    	}
		    	$message_model = new Message();
		    	$rs = $message_model->addAll($message_arr);
	      		if($rs) {
	      			DB::commit();
	      			return response()->json(['data'=>'','code'=>200,'message'=>'发送成功']);
	      		} 
	    	}
    	}catch(\Exception $e) {
    		DB::rollBack(); 
    		return response()->json(['code'=>400,'message'=>'发送失败']);
    	}
    }
    /*
    *获取消息用户列表
    */
    public function getUsers(Request $request) {
    	$user = Auth::user()->toArray();
    	$query = new User();
    	$fields = array('id','name','account','phone','email','type','companyId','usersignature');
    	$users = $query->where('id','<>',$user['id'])->get($fields)->toArray();

    	$return_data = array();
    	$return_data['data'] = $users;
        $return_data["code"] = 200;
        $return_data["message"] = 'success';
        return response()->json($return_data);
    }

    /*
    *已发送
    */
    public function sendMessageList(Request $request) {
    	$user = Auth::user()->toArray();

        $query = new MessageText();
        
        $data = $query->with(['message'])->whereHas('message', function ($query) use ($user){
            $query->where('from_id',$user['id']);
        })->orderBy('add_time','desc')->paginate($request->get('limit',20))->toArray();
       
    	$return_messages = array();
    	$return_messages = $this->filterSendMessageList($data);

    	$return_data = array();
    	$return_data['data'] = $return_messages['messages'];
        $return_data['total'] = $return_messages['total'];
        $return_data["code"] = 200;
        $return_data["message"] = '请求成功';
        return response()->json($return_data);
    }

    protected function filterSendMessageList($data) {
    	$return = array();
    	$return['total'] = $data['total'];
    	$messages = $data['data'];
    	/*获取用户信息*/
        $to_user_ids = array();
        $from_user_ids = array();
        foreach($messages as $k=>$v) {
            $to_ids = array_column($v['message'], 'to_id');
            $to_user_ids = array_merge($to_user_ids, $to_ids);
            $from_ids = array_column($v['message'], 'from_id');
            $from_user_ids = array_merge($from_user_ids, $from_ids);
        }
    	$to_user_ids = array_unique($to_user_ids);
    	$from_user_ids = array_unique($from_user_ids);
    	$user_ids = array_merge($to_user_ids,$from_user_ids);

    	$query = new User();
    	$users = $query->whereIn('id',$user_ids)->get()->toArray();
    	$users = array_column($users, NULL, 'id');
    	
    	$return['messages'] = array();
    	foreach($messages as $k=>$v) {
    		$tmp = $v;
            $message_user = $v['message'];
            foreach($message_user as $kk=>$vv) {
                $tmp['from'] = $users[$vv['from_id']]['name'];
                $tmp['to'] = isset($tmp['to'])?$tmp['to'].','.$users[$vv['to_id']]['name']:$users[$vv['to_id']]['name'];
            }
            unset($tmp['message']);
    		$tmp['add_time'] = date('Y-m-d H:i:s', $v['add_time']);
    		$return['messages'][] = $tmp;
    	}

    	return $return;
    }

    /*
    *收件箱
    */
    public function reciveMessageList(Request $request) {
    	$user = Auth::user()->toArray();
    	$message_text_model = new MessageText();
    	$message_text_table = $message_text_model->getTable();

    	$query = new Message();
    	$message_table = $query->getTable();

    	$fields = [$message_table.'.id',$message_table.'.from_id',$message_table.'.to_id',$message_table.'.message_id',$message_table.'.status',$message_text_table.'.title',$message_text_table.'.content',$message_text_table.'.attachment',$message_text_table.'.add_time'];
    	$data = $query->where('to_id', $user['id'])->leftjoin($message_text_table,$message_table.'.message_id',$message_text_table.'.id')->orderBy($message_text_table.'.add_time','desc')->paginate($request->get('limit',20),$fields)->toArray();

    	$return_messages = array();
    	$return_messages = $this->filterReciveMessageList($data);

    	$return_data = array();
    	$return_data['data'] = $return_messages['messages'];
        $return_data['total'] = $return_messages['total'];
        $return_data["code"] = 200;
        $return_data["message"] = '请求成功';
        return response()->json($return_data);
    }

    protected function filterReciveMessageList($data) {
    	$return = array();
    	$return['total'] = $data['total'];
    	$messages = $data['data'];
    	/*获取用户信息*/
    	$to_user_ids = array_column($messages, 'to_id');
    	$to_user_ids = array_unique($to_user_ids);
    	$from_user_ids = array_column($messages, 'from_id');
    	$from_user_ids = array_unique($from_user_ids);
    	$user_ids = array_merge($to_user_ids,$from_user_ids);

    	$query = new User();
    	$users = $query->whereIn('id',$user_ids)->get()->toArray();
    	$users = array_column($users, NULL, 'id');
    	
    	$return['messages'] = array();
    	foreach($messages as $k=>$v) {
    		$tmp = $v;
    		$tmp['from'] = $users[$v['from_id']]['name'];
    		$tmp['to'] = $users[$v['to_id']]['name'];
    		unset($tmp['from_id']);
    		unset($tmp['to_id']);
    		$tmp['add_time'] = date('Y-m-d H:i:s', $v['add_time']);
    		$return['messages'][] = $tmp;
    	}

    	return $return;
    }

    /*消息详情*/
    public function messageDetail(Request $request) {
    	$id = $request->get('id',0);
        $id_from = $request->get('id_from',0);
    	if(empty($id)||empty($id_from)) {
    		$return_data = array();
	        $return_data["code"] = 400;
	        $return_data["message"] = '缺少参数';
	        return response()->json($return_data);
    	}

        $user = Auth::user()->toArray();
        if($id_from==1) {/*传递的是message_text id 表示是发送者读取详情*/

            $message = Message::where(['from_id'=>$user['id'],'message_id'=>$id])->get();
            $message_arr = $message->toArray();
            $message_text = MessageText::findOrFail($id);
            $message_text_arr = $message_text->toArray();

            if(empty($message_arr)) {
                $return_data = array();
                $return_data["code"] = 400;
                $return_data["message"] = '消息不存在';
                return response()->json($return_data); 
            }

            $data = array();
            $data = $message_text_arr;
            $data['add_time'] = date('Y-m-d H:i:s', $data['add_time']);
            $data['from'] = $user['name'];

            $to_ids = array_column($message_arr, 'to_id');
            $query = new User();
            $users = $query->whereIn('id',$to_ids)->get()->toArray();//var_dump($users);exit;
            $to_user = '';
            foreach($users as $k=>$v) {
                $to_user = !empty($to_user)?$to_user.','.$v['name']:$v['name'];
            }
            $data['to'] = $to_user;

            $return_data['data'] = $data;
            $return_data["code"] = 200;
            $return_data["message"] = '获取信息成功';
            return response()->json($return_data);

        } elseif($id_from==2) {/*传递的是message id 表示是接收者读取详情*/
            $message = Message::findOrFail($id);
            $message_arr = $message->toArray();
            $message_text = MessageText::findOrFail($message['message_id']);
            $message_text_arr = $message_text->toArray();
            if($message['to_id']!=$user['id']) {
                $return_data["code"] = 400;
                $return_data["message"] = '您没有访问权限';
                return response()->json($return_data);
            }

            if($message['status']==0) {
                $message->update(array('status'=>1));
            }
            
            $data = array();
            $data = $message_text_arr;
            $data['add_time'] = date('Y-m-d H:i:s', $data['add_time']);
            unset($data['id']);

            $data = array_merge($message_arr, $data);
            $data['to'] = $user['name'];
            $from_user = User::findOrFail($message['from_id']);
            $data['from'] = $from_user['name'];

            $return_data['data'] = $data;
            $return_data["code"] = 200;
            $return_data["message"] = '获取信息成功';
            return response()->json($return_data);

        }
    }

}
